@using System.Web.Script.Serialization

@{
    Layout = "~/Views/Shared/_formTemplate.cshtml";
}

<script>
    var story = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

    var storyOptions = {
        fields: [{
            name: 'Title',
            type: 'textField',
            value: function (data) {
                return data.Title;
            },
            change: function (data, newText) {
                data.Title = newText;
            }
        }, {
            name: 'Summary',
            type: 'textAreaField',
            value: function (data) {
                return data.Summary;
            },
            change: function (data, newText) {
                data.Summary = newText;
            }
        }]
    };
    var sceneOptions = {
        fields: [{
            name: 'Scene',
            type: 'separator',
            buttons: [{
                text: 'Delete',
                action: deleteScene
            }, {
                text: 'Customize',
                action: customizeFields
            }]
        }, {
            name: 'Name',
            type: 'textField',
            value: function (data) {
                return data.Name;
            },
            change: function (data, newText) {
                data.Name = newText;
            }
        }, {
            name: 'Synopsis',
            type: 'textAreaField',
            value: function (data) {
                return data.Summary;
            },
            change: function (data, newText) {
                data.Summary = newText;
            }
        }, {
            name: 'Prose',
            type: 'textAreaField',
            value: function (data) {
                return data.Prose;
            },
            change: function (data, newText) {
                data.Prose = newText;
            }
        }]
    };

    var activeFields = ['Name', 'Synopsis'];

    var customizeOptions = {
        fields: [{
            name: 'Selected Fields',
            type: 'multiSelectField',
            values: $.map(sceneOptions.fields, function (element, index) {
                return { id: index, value: element.name, selected: $.inArray(element.name, activeFields) != -1 };
            }),
            onAdd: function (element) {
                activeFields[activeFields.length] = element.value;
            },
            onRemove: function (element) {
                activeFields = $.grep(activeFields, function (subElement) {
                    return subElement != element.value;
                });
            }
        }]
    };

    var placeHolderScene = {Id: -1};

    function deleteScene(field, data) {
        apprise('Are you sure want to delete this scene?', { 'confirm': true }, function (response) {
            if (!response) return;

            story.Scenes = $.grep(story.Scenes, function (element, index) {
                element.Order = index + 1;
                return element.Id != data.Id;
            });
            field.parent().remove();
        });
    }

    function save() {
        $.jsonSave('Save', story, function(newStory){story = newStory;});
    }

    function customizeFields() {
        $('#customize').dialog({
            height: 300,
            width: 600,
            buttons: { Save: saveCustomize }
        });
    }

    function saveCustomize() {
        $('#customize').dialog('close');

        reload();
    }

    function handleKeyup(event, element) {
        if (event.keyCode == 9) return;
        element.unbind('keyup');
        
        story.Scenes[story.Scenes.length] = placeHolderScene;
        placeHolderScene.Order = story.Scenes.length;
        placeHolderScene = {Id: placeHolderScene.Id - 1};
        addScene(placeHolderScene, true);
    }

    function addScene(scene, bindKeyup) {
        var activeOptions = {
            fields: $(sceneOptions.fields).filter(function (index) {
                return sceneOptions.fields[index].type == 'separator' ||
                    $.inArray(sceneOptions.fields[index].name, activeFields) != -1;
            })
        };

        var newDiv = $('<div class="innerDiv" id="div_' + scene.Id + '"/>');
        $('#fields').parent().append(newDiv);
        newDiv.buildUi($('#fieldMetadata'), activeOptions, scene);

        if (bindKeyup) newDiv.keyup(function(event) {handleKeyup(event, newDiv);});
    }

    function reload() {
        var parent = $('#fields').parent();
        parent.empty();
        parent.append($('<div class="innerDiv" id="fields"></div>'));

        $('#fields').buildUi($('#fieldMetadata'), storyOptions, story);

        $(story.Scenes)
            .sort(function(a, b) {
                return a.Order - b.Order;
            })
            .each(function (index, element) {
                element.Order = index + 1;
                addScene(element);
            });

        addScene(placeHolderScene, true);
    }

    function sortFromUI() {
        var orderLookup = new Object();
        $('.innerDiv:not(:first,:last)').each(function (index, element) {
            var divId = $(element).attr('id');
            orderLookup[parseInt(divId.replace('div_', ''), 10)] = index + 1;
        });
        $(story.Scenes).each(function (index, element) {
            element.Order = orderLookup[element.Id];
        });
    }

    $(function () {
        $('#customize').buildUi($('#fieldMetadata'), customizeOptions);

        reload();

        $('.outerDiv').sortable({
            items: "> div:not(#fields,:last)",
            stop: sortFromUI
        });
        $('.outerDiv').disableSelection();
    });
</script>

<div id="customize" style="display: none;">
</div>